package com.rc.saas.mini.controller.elec;

import com.github.pagehelper.PageInfo;
import com.rc.saas.base.MinipBaseController;
import com.rc.saas.mini.charge.ChargeService;
import com.rc.saas.mini.common.base.DataTResponse;
import com.rc.saas.mini.common.config.UpYunConfig;
import com.rc.saas.mini.common.constant.SessionConstants;
import com.rc.saas.mini.facede.ElecStationAssemble;
import com.rc.saas.mini.hlhtcec2.service.HlhtChargeService;
import com.rc.saas.mini.mapper.elec.ElecGunMapper;
import com.rc.saas.mini.minip.vo.LoginInfoVo;
import com.rc.saas.mini.model.elec.*;
import com.rc.saas.mini.model.member.MemberInfo;
import com.rc.saas.mini.model.order.OrderInfo;
import com.rc.saas.mini.model.order.OrderInfoExample;
import com.rc.saas.mini.model.platform.PlatformArea;
import com.rc.saas.mini.model.platform.PlatformCity;
import com.rc.saas.mini.model.platform.PlatformProvince;
import com.rc.saas.mini.model.rc.RcEvaluate;
import com.rc.saas.mini.model.rc.RcEvaluateExample;
import com.rc.saas.mini.model.tenant.Tenant;
import com.rc.saas.mini.model.tenant.TenantTicketStation;
import com.rc.saas.mini.model.tenant.TenantTicketStationExample;
import com.rc.saas.mini.search.ElecStationSearch;
import com.rc.saas.mini.service.elec.ElecGunService;
import com.rc.saas.mini.service.elec.ElecPileService;
import com.rc.saas.mini.service.elec.ElecStationPriceService;
import com.rc.saas.mini.service.elec.ElecStationService;
import com.rc.saas.mini.service.hlht.HlhtOperatorService;
import com.rc.saas.mini.service.hlht.HlhtOperatorSettingService;
import com.rc.saas.mini.service.hlht.HlhtTenantOpenService;
import com.rc.saas.mini.service.hlhtsk.HlhtskBizOperatorService;
import com.rc.saas.mini.service.hlhtsk.HlhtskTenantService;
import com.rc.saas.mini.service.member.MemberInfoService;
import com.rc.saas.mini.service.order.OrderInfoService;
import com.rc.saas.mini.service.platform.PlatformAreaService;
import com.rc.saas.mini.service.platform.PlatformCityService;
import com.rc.saas.mini.service.platform.PlatformProvinceService;
import com.rc.saas.mini.service.rc.RcEvaluateService;
import com.rc.saas.mini.service.tenant.TenantService;
import com.rc.saas.mini.service.tenant.TenantTicketStationService;
import com.rc.saas.mini.vo.elec.ElecStationExtInfo;
import com.rc.saas.mini.vo.elec.ElecStationInfoVo;
import com.rc.saas.mini.vo.elec.ElecStationPriceVo;
import com.rc.saas.mini.vo.elec.GunVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 桩群
 *
 * @author wangzhengwei
 * @create 2021/4/13
 */
@Api(tags = "08.站点（桩群）")
@Controller
@RequestMapping("/elecStation")
public class ElecStationController extends MinipBaseController {
    private static Logger logger = LogManager.getLogger(ElecStationController.class);

    @Autowired
    private ElecStationService elecStationService;

    @Autowired
    private MemberInfoService memberInfoService;

    @Autowired
    private TenantService tenantService;

    @Autowired
    private HlhtOperatorService hlhtOperatorService;

    @Autowired
    private UpYunConfig upYunConfig;

    @Autowired
    private ElecStationAssemble elecStationAssemble;

    @Autowired
    private OrderInfoService orderInfoService;

    @Autowired
    private HlhtskTenantService hlhtskTenantService;

    @Autowired
    private HlhtTenantOpenService hlhtTenantOpenService;

    @Autowired
    private HlhtskBizOperatorService hlhtskBizOperatorService;


    @Autowired
    private ElecGunService elecGunService;

    @Autowired
    private ElecPileService elecPileService;

    @Autowired
    private ChargeService chargeService;

    @Autowired
    private HlhtChargeService hlhtChargeService;

    @Autowired
    private HlhtOperatorSettingService hlhtOperatorSettingService;

    @Autowired
    private ElecStationPriceService elecStationPriceService;

    @Autowired
    private ElecGunMapper elecGunMapper;

    @Autowired
    private PlatformCityService platformCityService;

    @Autowired
    private PlatformProvinceService platformProvinceService;

    @Autowired
    private PlatformAreaService platformAreaService;
    @Autowired
    private RcEvaluateService rcEvaluateService;

    @Autowired
    private TenantTicketStationService tenantTicketStationService;

    /**
     * 全部站
     */
    @ResponseBody
    @RequestMapping("/open/listElecStation")
    @ApiOperation(value = "01 全部站", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiImplicitParams({
            //@ApiImplicitParam(name = "stationName", paramType = "query", value = "桩名", required = false),
            //@ApiImplicitParam(name = "stationBusyStatus", paramType = "query", value = "空闲站点(1:只显示空闲)", required = false),
            @ApiImplicitParam(name = "pileElecType", paramType = "query", value = "电桩类型(0 直流为快充，1 交流为慢充)", required = false),
            //@ApiImplicitParam(name = "stationType", paramType = "query", value = "桩群类型(1:公共,50:专用)", required = false),
            @ApiImplicitParam(name = "bizType", paramType = "query", value = "营业类型(0自营 1加盟商 2托管 3接口)", required = false),
            //@ApiImplicitParam(name = "isFreeParking", paramType = "query", value = "免费停车(0否 1是)", required = false),
            //@ApiImplicitParam(name = "Is24h", paramType = "query", value = "是否24小时营业(0 是 1否)", required = false),
            //@ApiImplicitParam(name = "isSpecialParking", paramType = "query", value = "是否专用车位(0 是 1否)", required = false),
            @ApiImplicitParam(name = "keyWord", paramType = "query", value = "桩群关键字(桩群名字，桩群编号，桩群地址 模糊搜索)", required = false),
            @ApiImplicitParam(name = "address", paramType = "query", value = "地址模糊查询", required = false),
            @ApiImplicitParam(name = "areaId", paramType = "query", value = "区域ID(可以传多个)", required = false),
            @ApiImplicitParam(name = "longitude", paramType = "query", value = "手机经度", required = false),
            @ApiImplicitParam(name = "latitude", paramType = "query", value = "手机纬度", required = false),
            @ApiImplicitParam(name = "ticketTypeId", paramType = "query", value = "优惠券id筛选", required = false),
            @ApiImplicitParam(name = "orderBy", paramType = "query", value = "排序(1距离最近,2距离最远,3 价格最低，4价格最高, 5评分最低，6评分最高)", required = false),
            //@ApiImplicitParam(name = "activeStation", paramType = "query", value = "只显示限时活动站点(0否，1是)", required = false),
            //@ApiImplicitParam(name = "availableCoupon", paramType = "query", value = "站点是否可用优惠券(0否，1是)", required = false),
            @ApiImplicitParam(name = "distance", paramType = "query", value = "查询距离(km)", required = false),})
    public DataTResponse<List<ElecStationInfoVo>> listElecStation(HttpServletRequest request, ElecStationSearch search) {

        LoginInfoVo loginInfo = readLoginInfo(request);
        MemberInfo member = new MemberInfo();


        String tenantCode = (String) request.getSession().getAttribute(SessionConstants.SESSION_TENANT);
        search.setTenantCode(tenantCode);
        if (tenantCode == null || StringUtils.isBlank(tenantCode)) {
            logger.error("找不到对应运营商信息:{},sessionId:{}", tenantCode, loginInfo.getToken());
            return DataTResponse.FAIL("找不到对应运营商信息");
        }
        //游客
        if (loginInfo == null) {
            member.setTenantCode(tenantCode);
        } else {
            member = memberInfoService.selectByPrimaryKey(loginInfo.getMemberId());
        }
        if(search.getTicketTypeId()!=null){
            List<Long> ids=new ArrayList<>();
            TenantTicketStationExample tenantTicketStationExample=new TenantTicketStationExample();
            tenantTicketStationExample.createCriteria().andTicketTypeIdEqualTo(search.getTicketTypeId());
            List<TenantTicketStation> tenantTicketStationList=tenantTicketStationService.selectByExample(tenantTicketStationExample);
            ids=tenantTicketStationList.stream().map(TenantTicketStation::getElecStationId).collect(Collectors.toList());
            if(ids.size()>0){
                search.setStationIdList(ids);
            }
        }
//        elecStationService.updateFlag();
        List<ElecStation> list = elecStationService.listElecStation(search);
        //最优价格（会员价，桩群优惠价，超级会员价，企业会员优惠价对比），快充，慢充，地区，电价信息
        List<ElecStationExtInfo> elecStationFindVos = elecStationAssemble.assembleStationExtInfo(tenantCode, member, list);
        //for (ElecStationExtInfo elecStationExtInfo : elecStationFindVos) {
        //    if (StringUtils.isNotBlank(elecStationExtInfo.getStationImg1())) {
        //        elecStationExtInfo.setStationImg1(upYunConfig.getDownloadRoot() + elecStationExtInfo.getStationImg1());
        //    }
        //    if (StringUtils.isNotBlank(elecStationExtInfo.getStationImg2())) {
        //        elecStationExtInfo.setStationImg2(upYunConfig.getDownloadRoot() + elecStationExtInfo.getStationImg2());
        //    }
        //    if (StringUtils.isNotBlank(elecStationExtInfo.getStationImg3())) {
        //        elecStationExtInfo.setStationImg3(upYunConfig.getDownloadRoot() + elecStationExtInfo.getStationImg3());
        //    }
        //    if (StringUtils.isNotBlank(elecStationExtInfo.getStationImg4())) {
        //        elecStationExtInfo.setStationImg4(upYunConfig.getDownloadRoot() + elecStationExtInfo.getStationImg4());
        //    }
        //    if (StringUtils.isNotBlank(elecStationExtInfo.getStationImg5())) {
        //        elecStationExtInfo.setStationImg5(upYunConfig.getDownloadRoot() + elecStationExtInfo.getStationImg5());
        //    }
        //}
        List<ElecStationInfoVo> elecStationInfoVos = new ArrayList<>();
        //BeanUtils.copyProperties(elecStationInfoVos, elecStationInfoVos);
        if (elecStationFindVos == null || elecStationFindVos.size() == 0) {
            return DataTResponse.SUCCESS();
        }
        elecStationFindVos.forEach(data -> {

            ElecStationInfoVo elecStationInfoVo = new ElecStationInfoVo();

            BeanUtils.copyProperties(data, elecStationInfoVo);
            Integer avg = rcEvaluateService.getavg(elecStationInfoVo.getElecStationId());
            if(avg == -1){
                avg = 100;
            }
            elecStationInfoVo.setStationStar(avg);

            elecStationInfoVos.add(elecStationInfoVo);
        });
        return DataTResponse.SUCCESS_DATA(elecStationInfoVos);
    }

    /**
     * 分页查找站
     */
    @ResponseBody
    @RequestMapping("/open/listPageElecStation")
    @ApiOperation(value = "02 分页查找站", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiImplicitParams({
            //@ApiImplicitParam(name = "stationName", paramType = "form", value = "桩名", required = false),
            //@ApiImplicitParam(name = "stationBusyStatus", paramType = "form", value = "空闲站点(1:只显示空闲)", required = false),
            @ApiImplicitParam(name = "pileElecType", paramType = "form", value = "电桩类型(0 直流为快充，1 交流为慢充)", required = false),
            //@ApiImplicitParam(name = "stationType", paramType = "form", value = "桩群类型(1:公共,50:专用)", required = false),
            @ApiImplicitParam(name = "bizType", paramType = "query", value = "营业类型(0自营 1加盟商 2托管 3接口)", required = false),
            //@ApiImplicitParam(name = "isFreeParking", paramType = "form", value = "免费停车(0否 1是)", required = false),
            //@ApiImplicitParam(name = "Is24h", paramType = "form", value = "是否24小时营业(0 是 1否)", required = false),
            //@ApiImplicitParam(name = "isSpecialParking", paramType = "form", value = "是否专用车位(0 是 1否)", required = false),
            @ApiImplicitParam(name = "keyWord", paramType = "form", value = "桩群关键字(桩群名字，桩群编号，桩群地址 模糊搜索)", required = false),
            @ApiImplicitParam(name = "address", paramType = "form", value = "地址模糊查询", required = false),
            @ApiImplicitParam(name = "areaId", paramType = "form", value = "区域ID(可以传多个)", required = false),
            @ApiImplicitParam(name = "longitude", paramType = "query", value = "手机经度", required = false),
            @ApiImplicitParam(name = "latitude", paramType = "query", value = "手机纬度", required = false),
            @ApiImplicitParam(name = "pageNo", paramType = "query", value = "页码（默认1）", required = false),
            @ApiImplicitParam(name = "pageSize", paramType = "query", value = "页大小（默认10）", required = false),
            @ApiImplicitParam(name = "orderBy", paramType = "form", value = "排序(1距离最近,2距离最远,3 价格最低，4价格最高, 5评分最低，6评分最高", required = false),
            //@ApiImplicitParam(name = "activeStation", paramType = "query", value = "只显示限时活动站点(0否，1是)", required = false),
            //@ApiImplicitParam(name = "availableCoupon", paramType = "query", value = "站点是否可用优惠券(0否，1是)", required = false),
            @ApiImplicitParam(name = "ticketTypeId", paramType = "query", value = "优惠券id筛选", required = false),
            @ApiImplicitParam(name = "distance", paramType = "query", value = "查询距离内(km)", required = false),})
    public DataTResponse<List<ElecStationInfoVo>> listPageElecStation(HttpServletRequest request, ElecStationSearch search,
                                                                      @RequestParam(value = "pageNo", defaultValue = "1") Integer pageNo,
                                                                      @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {
        LoginInfoVo loginInfo = readLoginInfo(request);
        String tenantCode = (String) request.getSession().getAttribute(SessionConstants.SESSION_TENANT);
        search.setTenantCode(tenantCode);
        if (tenantCode == null || StringUtils.isBlank(tenantCode)) {
            logger.error("找不到对应运营商信息:{}", tenantCode);
            return DataTResponse.FAIL("找不到对应运营商信息");
        }
        MemberInfo member = new MemberInfo();
        //游客
        if (loginInfo == null) {
            member.setTenantCode(tenantCode);
        } else {
            member = memberInfoService.selectByPrimaryKey(loginInfo.getMemberId());
        }


        if(search.getTicketTypeId()!=null){
            List<Long> ids=new ArrayList<>();
            TenantTicketStationExample tenantTicketStationExample=new TenantTicketStationExample();
            tenantTicketStationExample.createCriteria().andTicketTypeIdEqualTo(search.getTicketTypeId());
            List<TenantTicketStation> tenantTicketStationList=tenantTicketStationService.selectByExample(tenantTicketStationExample);
            ids=tenantTicketStationList.stream().map(TenantTicketStation::getElecStationId).collect(Collectors.toList());
            if(ids.size()>0){
                search.setStationIdList(ids);
            }
        }


//        elecStationService.updateFlag();
        search.setTenantCode(tenantCode);
        //CountPileVo countPileVo = new CountPileVo();
        ////是否只显示限时活动站点 0都显示 1只显示
        //if ("1".equals(search.getActiveStation())) {
        //    List<Long> activeStationList = elecStationService.listActiveStation(tenantCode);
        //    if (CollectionUtils.isEmpty(activeStationList)) {
        //        countPileVo.setElecStationFindVos(Collections.EMPTY_LIST);
        //        countPileVo.setPages(0);
        //        return DataTResponse.SUCCESS_DATA(countPileVo);
        //    }
        //    search.setActiveStationes(activeStationList);
        //
        //}
        ////是否只显示优惠券可用站点 0都显示 1只显示 (登陆之后才能筛选优惠券可用站点)
        //if ("1".equals(search.getAvailableCoupon()) && member.getMemberId() != null) {
        //    List<Long> couponStationList = elecStationService.listAvailableCouponStation(tenantCode, member.getMemberId());
        //    if (CollectionUtils.isEmpty(couponStationList)) {
        //        countPileVo.setElecStationFindVos(Collections.EMPTY_LIST);
        //        countPileVo.setPages(0);
        //        return DataTResponse.SUCCESS_DATA(countPileVo);
        //    }
        //    search.setCouponStationes(couponStationList);
        //}

        PageInfo<ElecStation> stationPageInfo = elecStationService.listPageElecStation(search, pageNo, pageSize);

        //if (stationPageInfo.getList().size() == 0) {
        //    countPileVo.setElecStationFindVos(Collections.EMPTY_LIST);
        //    countPileVo.setPages(0);
        //    return DataTResponse.SUCCESS_DATA(countPileVo);
        //}

        //最优价格（会员价，桩群优惠价，超级会员价，企业会员优惠价对比），快充，慢充，地区，电价信息
        //List<ElecStationExtInfo> elecStationFindVos = elecStationService.listElecStationFindVo(member, stationPageInfo.getList(), tenantCode);
        List<ElecStationExtInfo> elecStationFindVos = elecStationAssemble.assembleStationExtInfo(tenantCode, member, stationPageInfo.getList());
        //for (ElecStationExtInfo elecStationExtInfo : elecStationFindVos) {
        //    if (StringUtils.isNotBlank(elecStationExtInfo.getStationImg1())) {
        //        elecStationExtInfo.setStationImg1(upYunConfig.getDownloadRoot() + elecStationExtInfo.getStationImg1());
        //    }
        //    if (StringUtils.isNotBlank(elecStationExtInfo.getStationImg2())) {
        //        elecStationExtInfo.setStationImg2(upYunConfig.getDownloadRoot() + elecStationExtInfo.getStationImg2());
        //    }
        //    if (StringUtils.isNotBlank(elecStationExtInfo.getStationImg3())) {
        //        elecStationExtInfo.setStationImg3(upYunConfig.getDownloadRoot() + elecStationExtInfo.getStationImg3());
        //    }
        //    if (StringUtils.isNotBlank(elecStationExtInfo.getStationImg4())) {
        //        elecStationExtInfo.setStationImg4(upYunConfig.getDownloadRoot() + elecStationExtInfo.getStationImg4());
        //    }
        //    if (StringUtils.isNotBlank(elecStationExtInfo.getStationImg5())) {
        //        elecStationExtInfo.setStationImg5(upYunConfig.getDownloadRoot() + elecStationExtInfo.getStationImg5());
        //    }
        //
        //}

        //Long topId = null;
        //List<ElecStationExtInfo> elecStationFirst = new ArrayList<>();
        //List<ElecStationExtInfo> elecStationTemp = new ArrayList<>();
        //List<ElecStationExtInfo> elecStationTop = new ArrayList<>();
        //
        ////排序 1距离 2价格  3快充空闲多
        //if ("2".equals(search.getOrderBy())) {
        //    elecStationFindVos =
        //            elecStationFindVos.stream().sorted(Comparator.comparing(userBean -> userBean.getPvPrice())).collect(Collectors.toList());
        //} else if ("3".equals(search.getOrderBy())) {
        //    elecStationFindVos = elecStationFindVos.stream().sorted(Comparator.comparing(ElecStationExtInfo::getUsableQuickNum).reversed()).collect(Collectors.toList());
        //}
        //
        ////置顶功能 价格最低(首页)
        //for (ElecStationExtInfo elecStationExtInfo : elecStationFindVos) {
        //    if (elecStationExtInfo.getShowPlaceType() != null && "1".equals(elecStationExtInfo.getShowPlaceType()) && pageNo == 1) {
        //        elecStationTop.add(elecStationExtInfo);
        //    }
        //}
        //
        ////置顶1个
        //if (elecStationTop.size() > 0) {
        //    elecStationTop = elecStationTop.stream().sorted(Comparator.comparing(userBean -> userBean.getBestDiscount().getTotalDiscountPrice())).collect(Collectors.toList());
        //    topId = elecStationTop.get(0).getElecStationId();
        //    elecStationFirst.add(elecStationTop.get(0));
        //}
        //
        //for (ElecStationExtInfo elecStationExtInfo : elecStationFindVos) {
        //
        //    if (elecStationExtInfo.getElecStationId().equals(topId)) {
        //        continue;
        //    } else {
        //        elecStationTemp.add(elecStationExtInfo);
        //    }
        //}
        //
        //elecStationFirst.addAll(elecStationTemp);
        //countPileVo.setElecStationFindVos(elecStationFirst);
        //countPileVo.setPages(stationPageInfo.getPages());
        //DataTResponse DataTResponse = DataTResponse.SUCCESS();
        //DataTResponse.put(countPileVo);
        List<ElecStationInfoVo> elecStationInfoVos = new ArrayList<>();
        //BeanUtils.copyProperties(elecStationInfoVos, elecStationInfoVos);

        if (elecStationFindVos == null || elecStationFindVos.size() == 0) {
            return DataTResponse.SUCCESS();
        }
        elecStationFindVos.forEach(data -> {

            ElecStationInfoVo elecStationInfoVo = new ElecStationInfoVo();

            BeanUtils.copyProperties(data, elecStationInfoVo);
            Integer avg = rcEvaluateService.getavg(elecStationInfoVo.getElecStationId());
            if(avg == -1){
                avg = 100;
            }
            elecStationInfoVo.setStationStar(avg);

            elecStationInfoVos.add(elecStationInfoVo);
        });
        return DataTResponse.SUCCESS_DATA(elecStationInfoVos);
    }

    /**
     * 桩群详情
     */
    @RequestMapping(value = "/open/selectStationDetail", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "03.站详情", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "elecStationId", paramType = "query", value = "桩群ID", required = true),
            @ApiImplicitParam(name = "longitude", paramType = "query", value = "手机经度", required = false),
            @ApiImplicitParam(name = "latitude", paramType = "query", value = "手机纬度", required = false),
    })
    public DataTResponse<ElecStationInfoVo> selectStationDetail(HttpServletRequest request, ElecStationSearch search) {
        try {
            String tenantCode = (String) request.getSession().getAttribute(SessionConstants.SESSION_TENANT);
            if (search.getElecStationId() == null) {
                return DataTResponse.FAIL("参数为空");
            }
            if (tenantCode == null || StringUtils.isBlank(tenantCode)) {
                logger.error("找不到对应运营商信息:{}", tenantCode);
                return DataTResponse.FAIL("找不到对应运营商信息");
            }
            LoginInfoVo loginInfo = readLoginInfo(request);
            MemberInfo member = new MemberInfo();
            //游客
            if (loginInfo == null) {
                member.setTenantCode(tenantCode);
            } else {
                member = memberInfoService.selectByPrimaryKey(loginInfo.getMemberId());
            }
            search.setTenantCode(tenantCode);
            Tenant tenant = tenantService.selectByPrimaryKey(tenantCode);
            String tenantName = tenant.getTenantName();

            //ElecStationExtInfo elecStationFindVo = elecStationAssemble.selectStationDetail(member, elecStationId, longitude, latitude);
            //if (StringUtils.isNotBlank(elecStationFindVo.getStationImg1())) {
            //    elecStationFindVo.setStationImg1(upYunConfig.getDownloadRoot() + elecStationFindVo.getStationImg1());
            //}
            //if (StringUtils.isNotBlank(elecStationFindVo.getStationImg2())) {
            //    elecStationFindVo.setStationImg2(upYunConfig.getDownloadRoot() + elecStationFindVo.getStationImg2());
            //}
            //if (StringUtils.isNotBlank(elecStationFindVo.getStationImg3())) {
            //    elecStationFindVo.setStationImg3(upYunConfig.getDownloadRoot() + elecStationFindVo.getStationImg3());
            //}
            //if (StringUtils.isNotBlank(elecStationFindVo.getStationImg4())) {
            //    elecStationFindVo.setStationImg4(upYunConfig.getDownloadRoot() + elecStationFindVo.getStationImg4());
            //}
            //if (StringUtils.isNotBlank(elecStationFindVo.getStationImg5())) {
            //    elecStationFindVo.setStationImg5(upYunConfig.getDownloadRoot() + elecStationFindVo.getStationImg5());
            //}
            //
            //if (elecStationFindVo.getTenantCode() != null) {
            //    tenantName = tenantService.selectByPrimaryKey(elecStationFindVo.getTenantCode()).getTenantShortname();
            //}
            //if (elecStationFindVo.getHlhtOperatorId() != null) {
            //    tenantName = hlhtOperatorService.selectByPrimaryKey(elecStationFindVo.getHlhtOperatorId()).getHlhtOperatorName();
            //}

            //elecStationFindVo.setTenantName(tenantName);
            List<ElecStation> list = elecStationService.listElecStation(search);
            //最优价格（会员价，桩群优惠价，超级会员价，企业会员优惠价对比），快充，慢充，地区，电价信息
            List<ElecStationExtInfo> elecStationFindVos = elecStationAssemble.assembleStationExtInfo(tenantCode, member, list);
            if (elecStationFindVos == null || elecStationFindVos.size() == 0) {
                DataTResponse.FAIL("获取信息失败!");
            }
            if (elecStationFindVos.size() == 0) {
                return DataTResponse.SUCCESS();
            }

            ElecStationInfoVo elecStationInfoVo = new ElecStationInfoVo();
            BeanUtils.copyProperties(elecStationFindVos.get(0), elecStationInfoVo);

            if (elecStationInfoVo.getCityId() != null) {
                PlatformCity platformCity = platformCityService.selectByPrimaryKey(elecStationInfoVo.getCityId());
                elecStationInfoVo.setCityName(platformCity.getCityName());
            }
            if (elecStationInfoVo.getCityId() != null) {
                PlatformArea platformArea = platformAreaService.selectByPrimaryKey(elecStationInfoVo.getAreaId());
                elecStationInfoVo.setAreaName(platformArea.getAreaName());
            }
            if (elecStationInfoVo.getCityId() != null) {
                PlatformProvince platformProvince = platformProvinceService.selectByPrimaryKey(elecStationInfoVo.getProvinceId());
                elecStationInfoVo.setProvinceName(platformProvince.getProvinceName());
            }
            RcEvaluateExample rcEvaluateExample = new RcEvaluateExample();
            rcEvaluateExample.createCriteria().andStatusEqualTo("2").andIsDeleteEqualTo("0").andElecStationIdEqualTo(elecStationInfoVo.getElecStationId());
            List<RcEvaluate> rcEvaluateList = rcEvaluateService.selectByExample(rcEvaluateExample);

            elecStationInfoVo.setEvaluateSums(rcEvaluateList.size());
            Integer avg = rcEvaluateService.getavg(elecStationInfoVo.getElecStationId());
            if(avg == -1){
                avg = 100;
            }
            elecStationInfoVo.setStationStar(avg);
            return DataTResponse.SUCCESS_DATA(elecStationInfoVo);
            //return DataTResponse.SUCCESS_DATA(elecStationFindVos.get(0));
        } catch (Exception e) {
            logger.error(e.getMessage());
            return DataTResponse.FAIL("获取信息失败!");
        }
    }

//    /**
//     * 最近使用桩群列表
//     */
//    @ResponseBody
//    @RequestMapping("/listPageUsedRecentlyStation")
//    @ApiOperation(value = "最近使用桩群列表", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "longitude", paramType = "query", value = "手机经度", required = false),
//            @ApiImplicitParam(name = "latitude", paramType = "query", value = "手机纬度", required = false),
//            @ApiImplicitParam(name = "pageNo", paramType = "query", value = "页码（默认1）", required = false),
//            @ApiImplicitParam(name = "pageSize", paramType = "query", value = "页大小（默认10）", required = false)
//    })
//    public DataTResponse listPageUsedRecentlyStation(@ApiIgnore HttpSession session, ElecStationSearch search,
//                                                 @RequestParam(value = "pageNo", defaultValue = "1") Integer pageNo,
//                                                 @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {
//        String tenantCode = (String) request.getSession().getAttribute(SessionConstants.SESSION_TENANT);
//        if (tenantCode == null || StringUtils.isBlank(tenantCode)) {
//            logger.error("找不到对应运营商信息:{}", tenantCode);
//            return DataTResponse.FAIL("找不到对应运营商信息");
//        }
//        search.setTenantCode(tenantCode);
//
//        LoginInfoVo loginInfoVo = readLoginInfo(request);
//        search.setTenantCode(tenantCode);
//        if (loginInfoVo == null) {
//            return DataTResponse.FAIL_LOGIN();
//        }
//        MemberInfo member = memberInfoService.selectByPrimaryKey(loginInfoVo.getMemberId());
//        if (member == null) {
//            return DataTResponse.FAIL_LOGIN();
//        }
//        logger.info("ElecStationController.listPageUsedRecentlyStation.tenantCode:{}:mobile:{}", tenantCode, member.getMobile());
//
////        OrderInfoExample example = new OrderInfoExample();
////        example.createCriteria().andMemberIdEqualTo(member.getMemberId());
////        example.setOrderByClause("created_time desc");
//        List<OrderInfo> orderInfoList = orderInfoService.listOrderRecently(member.getMemberId());
//
//        CountPileVo countPileVo = new CountPileVo();
//        if (orderInfoList == null || orderInfoList.size() == 0) {
//            //方便app端操作（使用 Collections.EMPTY_LIST 解决内存性能问题）
//            countPileVo.setElecStationFindVos(Collections.EMPTY_LIST);
//            return DataTResponse.SUCCESS_DATA(countPileVo);
//        }
//
//        //根据会员订单信息的桩群ID查找桩群信息
//        List<Long> elecStationIds = new ArrayList<>(orderInfoList.stream().map(OrderInfo::getElecStationId).collect(Collectors.toSet()));
//
//        search.setStationIdList(elecStationIds);
//        PageInfo<ElecStation> stationPageInfo = elecStationService.listPageElecStation(search, pageNo, pageSize);
//
//        //最优价格（会员价，桩群优惠价，超级会员价，企业会员优惠价对比），快充，慢充，地区，电价信息
//        List<ElecStationExtInfo> elecStationFindVos = elecStationAssemble.assembleStationExtInfo(tenantCode, member, stationPageInfo.getList());
//
//        countPileVo.setElecStationFindVos(elecStationFindVos);
//        countPileVo.setPages(stationPageInfo.getPages());
//        return DataTResponse.SUCCESS_DATA(countPileVo);
//    }
//
//
//    /**
//     * 自己本身+运营商列表 listTenantSaas
//     * @param request
//     * @return
//     */
//    @ResponseBody
//    @RequestMapping("/open/listTenantSaas")
//    @ApiOperation(value = "自己本身+运营商列表", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
//    public DataTResponse listTenantSaas(@ApiIgnore HttpSession session,HttpServletRequest request) {
//        String tenantCode = (String) request.getSession().getAttribute(SessionConstants.SESSION_TENANT);
//        if (tenantCode == null || StringUtils.isBlank(tenantCode)) {
//            logger.error("找不到对应运营商信息:{}", tenantCode);
//            return DataTResponse.FAIL("找不到对应运营商信息");
//        }
//        Tenant currentTenant=tenantService.selectByTenantCode(tenantCode);
//        List<HlhtOperator> hlhtOperatorList = hlhtOperatorService.selectByHlhtType("1");
//
//
//        List<TenantSaasVo> returnList = new ArrayList<>();
//
//        //自身
//        TenantSaasVo current = new TenantSaasVo();
//        current.setShortName(currentTenant.getTenantShortname());
//        //当为自身时，将hlhtTenantCode和hlhtOperator设为self，方便查找桩群时判断运营商
//        current.setHlhtTenantCode("self");
//        current.setHlhtOperatorId("self");
//        returnList.add(current);
//
//        //所有正向
//        HlhtskBizOperatorExample example=new HlhtskBizOperatorExample();
//        example.createCriteria().andStatusEqualTo("0").andTenantCodeEqualTo(currentTenant.getTenantCode()).andHlhtTypeEqualTo("1");
//        List<HlhtskBizOperator> hlhtskBizOperatorList=hlhtskBizOperatorService.selectByExample(example);
//        hlhtOperatorList.forEach(hlhtOperator -> {
//            HlhtskBizOperator bizOperator=
//                    hlhtskBizOperatorList.stream().filter(hlhtskBizOperator -> hlhtskBizOperator.getHlhtOperatorId().equals(hlhtOperator.getHlhtOperatorId())).findFirst().orElseGet(()->null);
//            if(bizOperator!=null){
//                TenantSaasVo tenantSaasVo = new TenantSaasVo();
//                tenantSaasVo.setHlhtOperatorId(hlhtOperator.getHlhtOperatorId());
//                tenantSaasVo.setShortName(hlhtOperator.getHlhtOperatorShortname());
//                returnList.add(tenantSaasVo);
//            }
//
//        });
//        //所有saas反向
//        List<HlhtskTenant> hlhtskTenantList = hlhtskTenantService.listByTenantCodeAndTenantHlhtType(currentTenant.getTenantCode(), "1");
//        //List<HlhtTenantOpen> hlhtTenantOpenList = hlhtTenantOpenService.listHlhtTenantOpenByHlhtOpenType(currentTenant.getTenantCode(), "0", "0");
//        List<Tenant> tenantList = tenantService.listByStatus("0");
//        //saas
//        hlhtskTenantList.forEach(hlhtskTenant -> {
//            Tenant tenant = tenantList.stream().filter(tenant1 -> hlhtskTenant.getTenantCode().equals(tenant1.getTenantCode())).findFirst().orElseGet(() -> null);
//            //HlhtTenantOpen hlhtTenantOpen1 =
//            //        hlhtTenantOpenList.stream().filter(hlhtTenantOpen -> hlhtskTenant.getTenantCode().equals(hlhtTenantOpen.getTenantCode())).findFirst().orElseGet(() -> null);
//            //if (tenant != null && hlhtTenantOpen1 != null) {
//            if (tenant != null) {
//                TenantSaasVo tenantSaasVo = new TenantSaasVo();
//                tenantSaasVo.setHlhtTenantCode(tenant.getTenantCode());
//                tenantSaasVo.setShortName(tenant.getTenantShortname());
//                returnList.add(tenantSaasVo);
//            }
//        });
//        return DataTResponse.SUCCESS_DATA(returnList);
//    }

    /**
     * 单个桩价格信息
     */
    @RequestMapping("/open/selectTimeDiscount")
    @ResponseBody
    @ApiOperation(value = "单个站价格信息（明细）", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiImplicitParams({@ApiImplicitParam(name = "elecStationId", paramType = "query", value = "", required = false)})
    public DataTResponse<List<ElecStationPriceVo>> selectLevelDiscount(HttpServletRequest request, Long elecStationId) {
        String tenantCode = (String) request.getSession().getAttribute(SessionConstants.SESSION_TENANT);
        if (tenantCode == null || StringUtils.isBlank(tenantCode)) {
            logger.error("找不到对应运营商信息:{}", tenantCode);
            return DataTResponse.FAIL("找不到对应运营商信息");
        }
        if (elecStationId == null) {
            return DataTResponse.FAIL("请求参数异常");
        }

        LoginInfoVo loginInfo = readLoginInfo(request);
        MemberInfo member = new MemberInfo();
        //游客
        if (loginInfo == null) {
            member.setTenantCode(tenantCode);
        } else {
            member = memberInfoService.selectByPrimaryKey(loginInfo.getMemberId());
        }
        //MemberInfo member = memberInfoService.selectByPrimaryKey(12388L);

        //会员等级 tenant_ugs_member_level
        //MemberLeveDiscountVo memberLeveDiscountVo = elecStationService.selectTimeDiscount(member, elecStationId, redisTenantConfig.getTenantCode());
        //MemberLeveDiscountVo memberLeveDiscountVo = elecStationAssemble.selectTimeDiscount(tenantCode, member, elecStationId);
        ElecStationPriceExample example = new ElecStationPriceExample();
        example.createCriteria().andUsingStatusEqualTo("0").andElecStationIdEqualTo(elecStationId);
        example.setOrderByClause("begin_time ");

        List<ElecStationPrice> elecStationPriceList = elecStationPriceService.selectByExample(example);
        List<ElecStationPriceVo> elecStationPriceVoList = new ArrayList<>();
        elecStationPriceList.forEach(elecStationPrice -> {
            ElecStationPriceVo elecStationPriceVo = new ElecStationPriceVo();
            BeanUtils.copyProperties(elecStationPrice, elecStationPriceVo);
            elecStationPriceVoList.add(elecStationPriceVo);
        });

        return DataTResponse.SUCCESS_DATA(elecStationPriceVoList);
    }

    /**
     * 取指定桩群的枪列表
     *
     * @return
     */
    @RequestMapping("/open/listElecStationGun")
    @ResponseBody
    @ApiOperation(value = "指定站的枪列表（弃用）", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiImplicitParams({@ApiImplicitParam(name = "elecStationId", paramType = "query", value = "桩群ID", required = true)})
    public DataTResponse<List<GunVo>> listElecStationGun(HttpServletRequest request, Long elecStationId) {
        String tenantCode = (String) request.getSession().getAttribute(SessionConstants.SESSION_TENANT);
        if (tenantCode == null || StringUtils.isBlank(tenantCode)) {
            logger.error("找不到对应运营商信息:{}", tenantCode);
            return DataTResponse.FAIL("找不到对应运营商信息");
        }
        if (elecStationId == null) {
            return DataTResponse.FAIL("请求参数异常");
        }
        logger.info("ElecGunController.listElecStationGun.tenantCode:{},elecStationId:{}", tenantCode, elecStationId);

        List<ElecGun> gunList = elecGunService.listGunByStationId(elecStationId);
        List<ElecPile> elecPiles = elecPileService.selectByElecStationId(elecStationId);
        OrderInfoExample orderInfoExample = new OrderInfoExample();
        orderInfoExample.createCriteria().andStatusEqualTo("1").andElecStationIdEqualTo(elecStationId);
        List<OrderInfo> orderInfoList = orderInfoService.selectByExample(orderInfoExample);
        List<GunVo> list = new ArrayList<>();
        for (ElecGun gun : gunList) {
            GunVo vo = new GunVo(gun);
            BeanUtils.copyProperties(gun, vo);
            ElecPile pile = elecPiles.stream().filter(elecPile -> elecPile.getElecPileId().equals(gun.getElecPileId())).findFirst().orElseGet(() -> null);
            if (pile != null) {
                //运营中的桩
                if ("1".equals(pile.getOperateStatus())) {
                    vo.setPower(pile.getPower());
                    //vo.setPileType(String.valueOf(pile.getPileType()));
                    if (pile.getPileElecType() == 1 || pile.getPileElecType() == 3 || pile.getPileElecType() == 5 || pile.getPileElecType() == 6) {
                        vo.setPileType("0");
                    } else {
                        vo.setPileType("1");
                    }
                    //枪状态
                    if (gun.getElecPileId().equals(pile.getElecPileId())) {
                        //离线 使用状态 0 空闲 1使用中  2 插枪中  3故障 4 离线
                        if (0 == pile.getStatus()) {
                            vo.setUsingStatus(4);
                        } else {
                            //正常
                            if (0 == gun.getNormalStatus()) {
                                vo.setUsingStatus(gun.getStatus());
                                if (255 == vo.getUsingStatus()) {
                                    vo.setUsingStatus(3);
                                }
                            } else {
                                vo.setUsingStatus(3);
                            }
                        }
                    }
                    //是否在充电中

                    if (1 == gun.getStatus() && gun.getHlhtOperatorId() == null) {
                        vo.setSoc(new BigDecimal(chargeService.getCurrDataSoc(gun, tenantCode)));
                    }
                    if (1 == gun.getStatus() && gun.getHlhtOperatorId() != null) {
                        vo.setSoc(new BigDecimal(hlhtChargeService.getCurrDataSoc(gun, tenantCode, gun.getHlhtOperatorId())));
                    }
                    if (1 == gun.getStatus()) {
                        OrderInfo orderInfo = orderInfoList.stream().filter(data -> gun.getElecGunId().equals(data.getElecGunId())).findFirst().orElseGet(() -> null);
                        if (orderInfo != null) {
                            vo.setSurplusTime(chargeService.getRemainChargingTime(orderInfo.getOrderNum()));
                        }
                    }
                    list.add(vo);
                }
            }
        }
        return DataTResponse.SUCCESS_DATA(list);
    }

    /**
     * 取指定桩群的枪列表
     *
     * @return
     */
    @RequestMapping("/open/listByOther")
    @ResponseBody
    @ApiOperation(value = "指定站的枪列表(多条件查询)", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiImplicitParams(
            {
                    @ApiImplicitParam(name = "elecStationId", paramType = "query", value = "桩群ID", required = true),
                    @ApiImplicitParam(name = "pileType", paramType = "query", value = "0：快，1慢", required = false),
                    @ApiImplicitParam(name = "status", paramType = "query", value = "0 空闲 1使用中  2 插枪中 3已充满 默认所有", required = false),
                    @ApiImplicitParam(name = "nationalStandard", paramType = "query", value = "国标", required = false),

            })
    public DataTResponse<List<GunVo>> listByOther(HttpServletRequest request, Long elecStationId, String status, String pileType, String nationalStandard) {
        String tenantCode = (String) request.getSession().getAttribute(SessionConstants.SESSION_TENANT);
        if (tenantCode == null || StringUtils.isBlank(tenantCode)) {
            logger.error("找不到对应运营商信息:{}", tenantCode);
            return DataTResponse.FAIL("找不到对应运营商信息");
        }
        if (elecStationId == null) {
            return DataTResponse.FAIL("请求参数异常");
        }
        //logger.info("ElecGunController.listElecStationGun.tenantCode:{},elecStationId:{}", tenantCode, elecGun.getElecStationId());

        List<ElecGun> gunList = elecGunMapper.listByOther(elecStationId, status, pileType, nationalStandard);
        List<ElecPile> elecPiles = elecPileService.selectByElecStationId(elecStationId);

        OrderInfoExample orderInfoExample = new OrderInfoExample();
        orderInfoExample.createCriteria().andStatusEqualTo("1").andElecStationIdEqualTo(elecStationId);
        List<OrderInfo> orderInfoList = orderInfoService.selectByExample(orderInfoExample);

        List<GunVo> list = new ArrayList<>();
        for (ElecGun gun : gunList) {
            GunVo vo = new GunVo(gun);
            BeanUtils.copyProperties(gun, vo);
            ElecPile pile = elecPiles.stream().filter(elecPile -> elecPile.getElecPileId().equals(gun.getElecPileId())).findFirst().orElseGet(() -> null);
            if (pile != null) {
                //运营中的桩
                if ("1".equals(pile.getOperateStatus())) {
                    vo.setPower(pile.getPower());

                    if (pile.getPileElecType() == 1 || pile.getPileElecType() == 3 || pile.getPileElecType() == 5 || pile.getPileElecType() == 6) {
                        vo.setPileType("0");
                    } else {
                        vo.setPileType("1");
                    }

                    //枪状态
                    if (gun.getElecPileId().equals(pile.getElecPileId())) {
                        //离线 使用状态 0 空闲 1使用中  2 插枪中  3故障 4 离线
                        if (0 == pile.getStatus()) {
                            vo.setUsingStatus(4);
                        } else {
                            //正常
                            if (0 == gun.getNormalStatus()) {
                                vo.setUsingStatus(gun.getStatus());
                                if (255 == vo.getUsingStatus()) {
                                    vo.setUsingStatus(3);
                                }
                                if (3 == gun.getStatus()) {
                                    vo.setUsingStatus(5);
                                }
                            } else {
                                vo.setUsingStatus(3);
                            }
                        }
                    }
                    //是否在充电中

                    if (1 == gun.getStatus() && gun.getHlhtOperatorId() == null) {
                        vo.setSoc(new BigDecimal(chargeService.getCurrDataSoc(gun, tenantCode)));
                    }
                    if (1 == gun.getStatus() && gun.getHlhtOperatorId() != null) {
                        vo.setSoc(new BigDecimal(hlhtChargeService.getCurrDataSoc(gun, tenantCode, gun.getHlhtOperatorId())));
                    }
                    if (1 == gun.getStatus()) {
                        OrderInfo orderInfo = orderInfoList.stream().filter(data -> gun.getElecGunId().equals(data.getElecGunId())).findFirst().orElseGet(() -> null);
                        if(orderInfo!=null){
                            vo.setSurplusTime(chargeService.getRemainChargingTime(orderInfo.getOrderNum()));
                        }else{
                            vo.setSurplusTime("00:00:00");
                        }

                    }
                    list.add(vo);
                }
            }
        }
        return DataTResponse.SUCCESS_DATA(list);
    }

    ///**
    // * 拔枪结算桩提示语
    // */
    //@ResponseBody
    //@RequestMapping("/open/gunTips")
    //@ApiOperation(value = "拔枪结算桩提示语", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    //@ApiImplicitParams({@ApiImplicitParam(name = "hlhtOperatorId", paramType = "query", value = "hlhtOperatorId", required = true)})
    //public TResponse gunTips(String hlhtOperatorId) {
    //    if (StringUtils.isNotBlank(hlhtOperatorId)) {
    //        HlhtOperatorSettingExample example = new HlhtOperatorSettingExample();
    //        example.createCriteria().andHlhtOperatorIdEqualTo(hlhtOperatorId);
    //
    //        HlhtOperatorSetting hlhtOperatorSetting = hlhtOperatorSettingService.selectByExample(example).stream().findFirst().orElseGet(() -> null);
    //        if (hlhtOperatorSetting != null && "1".equals(hlhtOperatorSetting.getGunCloseType())) {
    //            return TResponse.SUCCESS_DATA("该站点充电结束后请及时拔枪，否则平台将无法结束充电页面并结算");
    //        }
    //    }
    //    return TResponse.SUCCESS();
    //}

}
